package com.myapp.myhome.activity;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.SaveCallback;
import com.myapp.myhome.utils.ACache;
import com.myapp.myhome.utils.AllUtils;
import com.myapp.myhome.utils.MyPreferences;
import com.myapp.myhome.R;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class CheckoutActivity extends BaseActivity {

	private Button btn_back;
	private TextView text_title;
	private Button btn_menu;
	List<AVObject> list;
	Set<String> siteno = new HashSet<String>();
	MyPreferences preferences;
	ArrayList<String> list_names = new ArrayList<String>();
	ArrayList<Bitmap> list_imgs = new ArrayList<Bitmap>();
	MyCheckoutAdapter adapter;
	private ProgressBar bar;

	private ListView mListView;
	private TextView text_count;
	private TextView text_allmoney;
	private Button btn_sure;

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case 1111:
				adapter = new MyCheckoutAdapter(CheckoutActivity.this);
				mListView.setAdapter(adapter);
				bar.setVisibility(View.GONE);
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_checkout);
		preferences = new MyPreferences(this);
		initTitle();
		initView();
	}

	private void initTitle() {
		btn_back = (Button) this.findViewById(R.id.titlebar_back);
		btn_back.setVisibility(View.VISIBLE);
		btn_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		text_title = (TextView) this.findViewById(R.id.titlebar_title);
		text_title.setText("结算中心");
		btn_menu = (Button) this.findViewById(R.id.titlebar_menu);
		btn_menu.setVisibility(View.VISIBLE);
		btn_menu.setText("结算记录");
	}

	private void initView() {
		text_count = (TextView) this.findViewById(R.id.checkout_text_count);
		text_allmoney = (TextView) this
				.findViewById(R.id.checkout_text_allmoney);
		bar = (ProgressBar) this.findViewById(R.id.progressBar1);
		btn_sure = (Button) this.findViewById(R.id.check_btn_sure);
		btn_sure.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showMyDialog();
			}
		});

		searchInfo();// 进来就查询一次
		mListView = (ListView) this.findViewById(R.id.check_listview);

	}

	// 理论上是将之前未结算的数据都取出来
	private void searchInfo() {
		AVQuery<AVObject> query = new AVQuery<AVObject>("Expenses");
		query.whereEqualTo("paystate", false);// 查询所有未结算的数据
		query.findInBackground(new FindCallback<AVObject>() {
			public void done(List<AVObject> avObjects, AVException e) {
				if (e == null) {
					text_count.setText(avObjects.size() + "");
					list = avObjects;
					handler.sendEmptyMessage(1111);
					getAllMoney();
				} else {
					Log.d("MyHome", "查询失败");
					AllUtils.showToast(CheckoutActivity.this, "查询错误");
				}
			}
		});
	}

	private void getAllMoney() {
		double allmoney = 0;
		if (list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				AVObject avlist = list.get(i);
				double money = Double.parseDouble(avlist.getString("money"));
				allmoney += money;
			}
			BigDecimal b = new BigDecimal(allmoney);
			allmoney = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
			text_allmoney.setText(allmoney + "");
		}
	}

	private void showMyDialog(){
		Builder mDialog=new Builder(CheckoutActivity.this);
		mDialog.setTitle("确认提交");
		mDialog.setMessage("是否结算？？？？");
		mDialog.setPositiveButton("是", new AlertDialog.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				//不知道可不可以用   不敢测试----经过目前的测试是成功的
				for (int i = 0; i < list.size(); i++) {
					final String objectId = list.get(i).getObjectId();
					updateState(objectId);
				}
				dialog.dismiss();
			}
		});
		mDialog.setNegativeButton("没钱", new AlertDialog.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		mDialog.create().show();
	}
	
	// 结算
	private void updateState(String objectId) {
		AVObject post = AVObject.createWithoutData("Expenses", objectId);
		// 更新属性
		post.put("paystate", true);
		// 保存
		post.saveInBackground(new SaveCallback() {

			@Override
			public void done(AVException arg0) {
				if (arg0 == null) {
					AllUtils.showToast(CheckoutActivity.this, "结算成功");
					searchInfo();
				} else {
					AllUtils.showToast(CheckoutActivity.this, "结算失败,请重试");
				}

			}
		});
	}

	/**
	 * 
	 * */
	class MyCheckoutAdapter extends BaseAdapter {
		private ACache mCache;
		LayoutInflater layout;
		MyHolder holder;

		public MyCheckoutAdapter(Context context) {
			layout = LayoutInflater.from(context);
			mCache = ACache.get(context);
			setList();
		}

		public void setList() {
			siteno = preferences.getList("302home");
			list_names = new ArrayList<String>(siteno);
			for (int i = 0; i < siteno.size(); i++) {
				Bitmap testBitmap = mCache.getAsBitmap(list_names.get(i));
				if (testBitmap == null) {
					testBitmap = BitmapFactory.decodeResource(
							CheckoutActivity.this.getResources(),
							R.drawable.tx_no);// 要是没有头像的话就是用这个头像

				}
				list_imgs.add(testBitmap);
			}
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list_names.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			if (convertView == null) {
				convertView = layout.inflate(R.layout.checkout_listview_item,
						null);
				holder = new MyHolder(convertView);
				convertView.setTag(holder);
			} else {
				holder = (MyHolder) convertView.getTag();
			}

			holder.item_text_name.setText(list_names.get(position) + "");
			holder.item_img.setImageBitmap(list_imgs.get(position));

			double xiaofei = getXiaofei(position);
			double yufu = getYufu(position);
			holder.item_text_xiaofei.setText(xiaofei + "");
			holder.item_text_yufu.setText(yufu + "");
			holder.item_text_jiesuan.setText(getJieSuan(xiaofei, yufu));
			return convertView;
		}

		// 获取个人总消费
		private double getXiaofei(final int pos) {
			/** 个人总消费 */

			double permoney = 0;
			for (int i = 0; i < list.size(); i++) {
				if (list.get(i).getString("who").contains(list_names.get(pos))) {
					AVObject avlist = list.get(i);
					double money = Double.parseDouble(avlist
							.getString("avgpay"));
					permoney += money;
				}
			}
			System.out.println(permoney + "****");
			BigDecimal b = new BigDecimal(permoney);
			permoney = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
			return permoney;
		}

		// 获取预付金额
		private double getYufu(final int pos) {
			double yufu_money = 0;
			for (int i = 0; i < list.size(); i++) {
				if (list.get(i).getString("whopay")
						.contains(list_names.get(pos))) {
					AVObject avlist = list.get(i);
					double money = Double
							.parseDouble(avlist.getString("money"));
					yufu_money += money;
				}

			}
			BigDecimal b = new BigDecimal(yufu_money);
			yufu_money = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
			return yufu_money;
		}

		// 获取当前是赚了还是赔了
		private String getJieSuan(double xiaofei, double yufu) {
			double js = xiaofei - yufu;
			js = xiaofei - yufu;
			BigDecimal b = new BigDecimal(js);
			js = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
			if (xiaofei >= yufu) {
				return "需上交:" + js;
			} else {
				return "可取出:" + (-js);
			}

		}

		class MyHolder {
			ImageView item_img;
			TextView item_text_name;
			TextView item_text_xiaofei;
			TextView item_text_yufu;
			TextView item_text_jiesuan;

			public MyHolder(View view) {
				item_img = (ImageView) view
						.findViewById(R.id.checkout_item_img);
				item_text_name = (TextView) view
						.findViewById(R.id.checkout_item_text_name);
				item_text_xiaofei = (TextView) view
						.findViewById(R.id.checkout_item_text_xiaofei);
				item_text_jiesuan = (TextView) view
						.findViewById(R.id.checkout_item_text_jiesuan);
				item_text_yufu = (TextView) view
						.findViewById(R.id.checkout_item_text_yufu);
			}
		}
	}

}
